package ThreadDemo;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-29
 * Time: 14:12
 */
public class AtomicClassTest {
    public static void main(String[] args) throws InterruptedException {
        //原子类是基于CAS实现，所以进行++，--操作，只涉及到一条CPU指令，不需要进行加锁来保证线程安全
        //设置初始值
        AtomicInteger count = new AtomicInteger(0);
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //调用方法实现++操作
                count.getAndAdd(1);
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                //调用方法实现++操作
                count.getAndAdd(1);
            }
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("count = " + count);
    }
}
